﻿using DevExpress.LookAndFeel.Design;
using Newtonsoft.Json;
using PanhuaWin.NCModel;
using PanhuaWin.WMS2NC888;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PanhuaWin.超级管理员
{
    public partial class Form调拨出库 : UIPage
    {
        public Form调拨出库()
        {
            InitializeComponent();
        }

        private void uiButton查询_Click(object sender, EventArgs e)
        {
            query();
        }

        private void query()
        {
            string sql = @"select Bus_TransferV.[guid],  Bus_TransferV.[WorkShopName] 公司名称, Bus_TransferV.[DocCode] 提单单号,Bus_TransferV.ShipNo 船次, Bus_TransferV.[DeliveryDate] 发货日期, 
                            Bus_TransferV.[DepartmentName] 部门,Bus_TransferV.[CustomerName] 客户, 
                            [CreatorName] 制单人,   [Remark] 备注,
                            Bus_TransferVolume.[bguid],Bus_TransferVolume.DocCode NC提货单号, Bus_TransferVolume.[RowNumber] 行号, Bus_TransferVolume.[VolumeNumber] 卷号, Bus_TransferVolume.[InventoryCode] 存货编号,
                            Bus_TransferVolume.[WarehouseName] 仓库,
                            Bus_TransferVolume.[Size] 规格, Bus_TransferVolume.[Weight] 重量, Bus_TransferVolume.[status] 状态,[Chepai] 车牌,Bus_TransferVolume.Modifier 扫码出库人员,
                            Bus_TransferVolume.ModifyDate 扫码出库时间
                            from Bus_TransferV
                            left join Bus_TransferVolume 
                            on Bus_TransferV.guid = Bus_TransferVolume.guid where 1=1 ";

            if (!string.IsNullOrEmpty(uiTextBox发货单号.Text.Trim()))
            {
                sql += " and Bus_TransferV.DocCode like '%" + uiTextBox发货单号.Text.Trim() + "%'";
            }

            if (!string.IsNullOrEmpty(uiTextBox卷号.Text.Trim()))
            {
                sql += " and Bus_TransferVolume.[VolumeNumber] like '%" + uiTextBox卷号.Text.Trim() + "%'";
            }

            if (uiRadioButton未出库.Checked)
            {
                sql += " and Bus_TransferVolume.[status] is null";
            }

            if (uiRadioButton已出待放.Checked)
            {
                sql += " and Bus_TransferVolume.[status] = '已出库待放行'";
            }

            if (uiRadioButton已出已放.Checked)
            {
                sql += " and Bus_TransferVolume.[status] = '已出库已放行'";
            }
            if (!string.IsNullOrEmpty(uiTextBox车牌.Text))
            {
                sql += " and Bus_TransferVolume.Chepai like '%" + uiTextBox车牌.Text + "%'";
            } 
            if (!string.IsNullOrEmpty(uiTextBox船次.Text))
            {
                sql += " and Bus_TransferV.ShipNo like '%" + uiTextBox船次.Text + "%'";
            }
            //if (checkBox已出库.Checked)
            //{
            //    sql += "and Bus_TransferVolume.[status] is not null";
            //}
            //else
            //{
            //    sql += "and Bus_TransferVolume.[status] is  null";
            //}
            sql += " and Bus_TransferV.[DeliveryDate] >= '" + uiDatePicker开始日期.Value + "' and Bus_TransferV.[DeliveryDate] < '" + uiDatePicker结束日期.Value.AddDays(1) + "'";
            sql += " order by Bus_TransferV.[DocCode],Bus_TransferV.[DeliveryDate]";

            DataTable dt = pub.GetDataTable(pub.ConnectionString, sql);
            uiDataGridView发货.DataSource = dt;
            uiDataGridView发货.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            uiDataGridView发货.Refresh();
        }

        private async void uiButton手动发货_ClickAsync(object sender, EventArgs e)
        {
            //检查有没有填写原因
            if (string.IsNullOrEmpty(uiTextBox原因.Text.Trim()))
            {
                MessageBox.Show("请填写原因");
                return;
            }
            //选择的
            if (uiDataGridView发货 != null && uiDataGridView发货.Rows != null && uiDataGridView发货.Rows.Count > 0)
            {
                if (MessageBox.Show("确定将选择的发货单直接发货？此操作不可恢复，后果自负！！！", "警告！", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    for (int i = 0; i < uiDataGridView发货.Rows.Count; i++)
                    {
                        if (uiDataGridView发货.Rows[i].Cells["C选择"].Value != null && (bool)uiDataGridView发货.Rows[i].Cells["C选择"].Value)
                        {
                            //取值
                            string 提单单号 = uiDataGridView发货.Rows[i].Cells["C提单单号"].Value.ToString();
                            string csalereceiveid = uiDataGridView发货.Rows[i].Cells["CNC提货单号"].Value.ToString();

                            string rowNo = uiDataGridView发货.Rows[i].Cells["Cbguid"].Value.ToString();
                            string cinvbascode = uiDataGridView发货.Rows[i].Cells["C存货编号"].Value.ToString();
                            string vbatchcode = uiDataGridView发货.Rows[i].Cells["C卷号"].Value.ToString();
                            string nnum = uiDataGridView发货.Rows[i].Cells["C重量"].Value.ToString();
                            string csalereceiveidbid = uiDataGridView发货.Rows[i].Cells["C行号"].Value.ToString();

                            string 工厂名称 = uiDataGridView发货.Rows[i].Cells["C公司名称"].Value.ToString();

                            //发送NC回调接口的dto
                            //发送NC回调接口的dto
                            OtherOutboundDTO otherOutboundDTO = new OtherOutboundDTO();
                            otherOutboundDTO.docCode = csalereceiveid;
                            otherOutboundDTO.rowNumber = csalereceiveidbid;
                            otherOutboundDTO.rowNo = rowNo;
                            otherOutboundDTO.nnum = nnum;
                            otherOutboundDTO.ncLot = vbatchcode;
                            otherOutboundDTO.region = "华中";

                            ExternalSystemToNcItfPortTypeClient client = new ExternalSystemToNcItfPortTypeClient();

                            string jsonStr = JsonConvert.SerializeObject(otherOutboundDTO);
                            var response = await  client.addOtherOutboundAsync(jsonStr);
                            NCResponseModel nCResponseModel = JsonConvert.DeserializeObject<NCResponseModel>(response.@return);
                            if (nCResponseModel != null && nCResponseModel.state == 0)
                            {
                                //插入发货记录
                                string sql = @"INSERT INTO [dbo].[Bus_NCdelivery]
                                                           ([guid],[提单单号],[工厂名称],[提单行号],[存货编号]
                                                          ,[成品卷号],[备注],[DeliveryVolumebguid],状态,[CreateID],[Creator])     VALUES";
                                sql += @"(NEWID(),'" + 提单单号 + "','" + 工厂名称 + "','" + csalereceiveidbid + "','" + cinvbascode +
                                                        "','" + vbatchcode + "','" + uiTextBox原因.Text.Trim() + "','" + rowNo + "','已出库已放行','"
                                                        + pub.sys_user.User_Id + "','" + pub.sys_user.UserName + "');";
                                //更新NC发货单
                                sql += @"update Bus_TransferVolume set  status = '已出库已放行' ,HandleMan = '" + pub.sys_user.UserName +
                                        "',HandleReason = '" + uiTextBox原因.Text.Trim() + "',HandleTime = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                                        + "' where bguid = '" + rowNo + "';";
                                //更新在库状态
                                sql += @"update Bus_Volume set IsInStorage = '出库' where VolumeCodeNew = '" + vbatchcode + "';";
                                int r = pub.ExecuteSql(pub.ConnectionString, sql, "手动直接发货");
                                if (r < 1)
                                {
                                    MessageBox.Show("更新手动发货状态失败");
                                }
                            }
                            else
                            {
                                MessageBox.Show("推送NC失败：" + nCResponseModel.msg);
                            }
                        }
                    }
                }
            }
            query();
        }

        private void uiButton改为已出库已放行_Click(object sender, EventArgs e)
        {
            //检查有没有填写原因
            if (string.IsNullOrEmpty(uiTextBox原因.Text.Trim()))
            {
                MessageBox.Show("请填写原因");
                return;
            }
            if (MessageBox.Show("确定将选择的发货单改为已出库已放行？此操作不可恢复，后果自负！！！", "警告！", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                for (int i = 0; i < uiDataGridView发货.Rows.Count; i++)
                {
                    if (uiDataGridView发货.Rows[i].Cells["C选择"].Value != null && (bool)uiDataGridView发货.Rows[i].Cells["C选择"].Value)
                    {
                        string bguid = uiDataGridView发货.Rows[i].Cells["Cbguid"].Value.ToString();
                        string 卷号 = uiDataGridView发货.Rows[i].Cells["C卷号"].Value.ToString();
                        string sql = @"update Bus_TransferVolume set status = '已出库已放行',HandleMan = '" + pub.sys_user.UserName +
                                        "',HandleReason = '" + uiTextBox原因.Text.Trim() + "',HandleTime = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                                        + "' where bguid = '" + bguid + "';";
                        sql += @"update Bus_NCdelivery set 状态 = '已出库已放行' where DeliveryVolumebguid = '" + bguid + "';";
                        sql += @"update Bus_Volume set IsInStorage = '出库' where VolumeCodeNew = '" + 卷号 + "';";
                        int r = pub.ExecuteSql(pub.ConnectionString, sql, "手动改为已发货已出库");
                        if (r < 1)
                        {
                            MessageBox.Show("更新状态失败");
                        }
                    }
                }
            }
            query();
        }

        private void uiButton改为未发货_Click(object sender, EventArgs e)
        {
            //检查有没有填写原因
            if (string.IsNullOrEmpty(uiTextBox原因.Text.Trim()))
            {
                MessageBox.Show("请填写原因");
                return;
            }
            if (MessageBox.Show("确定将选择的发货单改为未发货？此操作不可恢复，后果自负！！！", "警告！", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                for (int i = 0; i < uiDataGridView发货.Rows.Count; i++)
                {
                    if (uiDataGridView发货.Rows[i].Cells["C选择"].Value != null && (bool)uiDataGridView发货.Rows[i].Cells["C选择"].Value)
                    {
                        string bguid = uiDataGridView发货.Rows[i].Cells["Cbguid"].Value.ToString();
                        string 卷号 = uiDataGridView发货.Rows[i].Cells["C卷号"].Value.ToString();
                        string sql = @"update Bus_DeliveryVolume set status = null,Chepai = null ,HandleMan = '" + pub.sys_user.UserName +
                                        "',HandleReason = '" + uiTextBox原因.Text.Trim() + "',HandleTime = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                                        + "' where bguid = '" + bguid + "';";
                        sql += @"delete from  Bus_NCdelivery  where DeliveryVolumebguid = '" + bguid + "';";
                        sql += @"update Bus_Volume set IsInStorage = '在库' where VolumeCodeNew = '" + 卷号 + "';";
                        int r = pub.ExecuteSql(pub.ConnectionString, sql, "手动改为已发货已出库");
                        if (r < 1)
                        {
                            MessageBox.Show("更新状态失败");
                        }
                    }
                }
            }
            query();
        }

        private void Form调拨出库_Load(object sender, EventArgs e)
        {
            uiDataGridView发货.AutoGenerateColumns = false;
            uiDatePicker开始日期.Value = DateTime.Today;
            uiDatePicker结束日期.Value = DateTime.Today;
            uiRadioButton已出待放.Checked = true;
            uiDatePicker实际发货日期.Value = DateTime.Today;
        }
    }
}
